package com.queclink.ycm.model;

import com.queclink.ycm.common.utils.DataUtil;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jim.li
 * @email jim.li@queclink.com
 * @date 2022-01-10 09:29:00
 */
public class NettyClient {

    private final Logger logger = LoggerFactory.getLogger(NettyClient.class);

    //设备ID
    private String uniqueId;
    //连接上下文
    private ChannelHandlerContext ctx;
    //最近通信时间
    private long time = System.currentTimeMillis();

    public static  final Map<String, ChannelSession> client = new ConcurrentHashMap<String, ChannelSession>(500000);

    public static ChannelSession getClient(String uniqueId) {
        return client.get(uniqueId);
    }

    public static void addClient(ChannelSession session) {
        client.put(session.getUnqiuedId(), session);
    }

    public static void remove(ChannelHandlerContext ctx) {
        for (Map.Entry<String, ChannelSession> entry : client.entrySet()) {
            String key = entry.getKey();
            ChannelSession value = entry.getValue();
            if (value.getCtx() == ctx) {
                System.out.println(DataUtil.getNowFormatDate() + " [" + key + "] Disconnect");
                client.remove(key);
                break;
            }
        }
    }

    public static boolean isExistUser(String uniqueId) {
        return client.containsKey(uniqueId);
    }

    public static Map<String, ChannelSession> getAllUser() {
        return client;
    }

    public String getUniqueId() {
        return uniqueId;
    }

    public void setUniqueId(String uniqueId) {
        this.uniqueId = uniqueId;
    }

    public ChannelHandlerContext getCtx() {
        return ctx;
    }

    public void setCtx(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public void sendMsgToClient(String msg) {
        this.setTime(System.currentTimeMillis());
        logger.info("向客户端发送数据：{}", msg);
        System.out.println("NettyClient向客户端发送数据！" + msg);
        System.out.println("NettyClient中：deviceId=" + this.uniqueId + "ctx:" + this.ctx.channel().isActive() + this.ctx.channel().isWritable());
        if (this.getCtx() != null && this.getCtx().channel().isWritable()) {
            System.out.println("向设备发送报文！AT+GTGEO=gl300,0,3,101.412248,21.187891,1000,600,,,,,,,,,0008$");
//			this.getCtx().writeAndFlush("AT+GTGEO=gl300,0,3,101.412248,21.187891,1000,600,,,,,,,,,0008$");
            this.getCtx().writeAndFlush(msg.getBytes());
        } else {
            logger.info("通道不可用或已经关闭！");
        }
    }
}
